package rss.util;

import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import org.xmlrpc.android.XMLRPCException;
import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndContent;
import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndEntry;
import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndFeed;
import com.google.code.rome.android.repackaged.com.sun.syndication.io.SyndFeedInput;
import com.google.code.rome.android.repackaged.com.sun.syndication.io.XmlReader;

public class LettoreRSS {

	private SyndFeed feed;
	private Iterator<SyndEntry> items;
	private LinkedList<FeedRSS> listaFeedRSS;
	ArrayList<Integer> arrayPostID;
	int countRSS;

	//La nostra sorgente Feed
	URL url;
	XmlReader reader = null;
	
	public LettoreRSS() {
		// TODO Auto-generated constructor stub
		
	}
	

	public void setLettoreRSS()throws Exception{

		url  = new URL("http://noigiovani.it/feed/");
		
		//Istanziamo uno stream reader dall'url della nostra sorgente feed
		reader = new XmlReader(url);

		//Diamo in pasto il nostro reader al parser RSS
		feed = new SyndFeedInput().build(reader);

		items=getItemsIterator();
		
		setCountRSS();
		riempiListaRSS();
	}

	public String getTitoloFeed()
	{
		return feed.getTitle();
	}


	public Iterator<SyndEntry> getItemsIterator()
	{
		Iterator<SyndEntry> it = feed.getEntries().iterator();
		return it;
	}

	public int riempiListaRSS() throws XMLRPCException
	{
		listaFeedRSS=new LinkedList<FeedRSS>();
		MyWordpress w=new MyWordpress();
		ArrayList<Integer> arrayPostID=w.generaArrayPostID(countRSS);

		int i=0;
		while(items.hasNext())
		{
			SyndEntry entry = items.next();
			listaFeedRSS.add(new FeedRSS(entry.getTitle(), entry.getPublishedDate(),entry.getAuthor(), entry.getDescription().getValue(), getContent(entry), entry.getLink(), arrayPostID.get(i)));			
			i++;
		}
		return listaFeedRSS.size();
	}

	public String getContent(SyndEntry entry)
	{
		String contentString=new String();
		for (Iterator<SyndContent> i = entry.getContents().iterator(); i.hasNext();)
		{
			SyndContent content = i.next();
			contentString=contentString+content.getValue();
		}
		return contentString;
	}

	public LinkedList<FeedRSS> getListaFeedRSS()
	{
		return listaFeedRSS;
	}
	
	public void setCountRSS()
	{
		countRSS=feed.getEntries().size();
	}
	
	public int getCountRSS()
	{
		return countRSS;
	}


}